package org.publictransport.server.service.data;

import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;


import com.google.appengine.api.datastore.Key;

/**
 * Singleton for handling datas
 * (shouldnt be instantieted more than once)
 * holds a persistencemanagerfactory
 * @author rasztasd
 *
 */
public class DataService {
	private static DataService instance;
	private final PersistenceManagerFactory persistenceManagerFactory = JDOHelper.getPersistenceManagerFactory("transactions-optional");
	private DataService() {
		
	}
	private PersistenceManagerFactory getManagerFactory() {
		return persistenceManagerFactory;
	}
	private PersistenceManager getPersistenceManager() {
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		return pm;
	}
	public void saveTransportLine(TransportLine line) {
		PersistenceManager pm = getPersistenceManager();
		try {
			pm.makePersistent(line);		
		} finally {
			pm.close();
		}
	}
	public TransportLine getTransportLine(int id) {
		PersistenceManager pm = getPersistenceManager();
		try {
			String query = "select from " + TransportLine.class.getName();
			TransportLine line = (TransportLine) pm.newQuery(query);
			return line;
		} finally {
			pm.close();
		}
	}
	public List<TransportLine> getTransportLines() {
		PersistenceManager pm = getPersistenceManager();
		return (List<TransportLine>) pm.newQuery("select from " + TransportLine.class.getName()).execute();
	}
	public static DataService getInstance() {
		if (instance == null) {
			instance = new DataService(); 
		}
		return instance;
	}
}
